package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Leaves;
import com.example.utils.MD5Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Department;
import com.example.entity.Employee;
import com.example.exception.CustomException;
import com.example.mapper.EmployeeMapper;
import com.example.service.DepartmentService;
import com.example.service.EmployeeService;
import com.example.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author dingchunlin
 * @Date 2023/12/27 20:35
 * @Version 1.0.0
 */
@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentService departmentService;

    @Override
    public Employee login(Employee employee) {
        //首先判断用户名是否已存在
        String username = employee.getUsername();
        Employee result = employeeMapper.selectByUserName(username);
        //判断查询结果是否为空,为空抛出用户不存在异常
        if (ObjectUtil.isEmpty(result)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        //将用户输入的密码进行处理
        employee.setPassword(MD5Utils.md5(employee.getPassword()));
        //进行判断用户密码是否正确
        if (!result.getPassword().equals(employee.getPassword())){
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        Employee resp = selectById(result.getId());
        // 生成token
        String tokenData = resp.getId() + "-" + RoleEnum.USER.name();
        String token = TokenUtils.createToken(tokenData, resp.getPassword());
        resp.setToken(token);
        return resp;
    }

    @Override
    public Employee selectById(Integer id) {
        Employee employee = baseMapper.selectById(id);
        if (ObjectUtil.isNotEmpty(employee)){
            Integer departmentId = employee.getDepartmentId();
            Department department = departmentService.selectById(departmentId);
            if (ObjectUtil.isNotEmpty(department)){
                employee.setDepartmentName(department.getDepartName());
            }
        }
        return employee;
    }

    @Override
    public List<Integer> selectIdByDepartmentId(Integer id) {
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getDepartmentId,id);
        List<Employee> employeeList = employeeMapper.selectList(lambdaQueryWrapper);
        List<Integer> ids = employeeList.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        return ids;
    }

    @Override
    public Employee selectByDepartmentIdAndRole(Integer departmentId, String role) {
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getDepartmentId,departmentId);
        lambdaQueryWrapper.eq(Employee::getRole,role);
        Employee employee = baseMapper.selectOne(lambdaQueryWrapper);
        return employee;
    }

    @Override
    public void add(Employee employee) {
        //首先判断用户名是否重复
        Employee res = employeeMapper.selectByUserName(employee.getUsername());

        //如果不为空抛出异常
        if (ObjectUtil.isNotEmpty(res)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        //判断用户是否有密码，没有则默认123456;
        if (ObjectUtil.isEmpty(employee.getPassword())){
            employee.setPassword(Constants.USER_DEFAULT_PASSWORD);
        }
        //判断用户是否输入了姓名，没有就设置为用户名
        if (ObjectUtil.isEmpty(employee.getName())){
            employee.setName(employee.getUsername());
        }
        //将用户的密码进行加密
        employee.setPassword(MD5Utils.md5(employee.getPassword()));
        //设置用户头像
        employee.setAvatar(Constants.AVATAR_URL);
        //设置员工号

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 定义日期格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将日期转换为字符串
        String dateStr = currentDate.format(formatter);
        dateStr = dateStr.replaceAll("-", "");
        log.info("dateStr:{}",dateStr);
        List<Employee> employeeList = employeeMapper.selectByEmployeeNumberEmployees(dateStr);
        if (ObjectUtil.isNotEmpty(employeeList)) {
            Integer maxNum = new Integer(0);
            for (Employee emp : employeeList) {
                String employeeNumber = emp.getEmployeeNumber();
                maxNum = Integer.parseInt(employeeNumber.substring(8));
            }
            if (maxNum < 10){
                employee.setEmployeeNumber(dateStr + "0" + (maxNum + 1));
            }else {
                employee.setEmployeeNumber(dateStr + (maxNum + 1));
            }
        }else {
            employee.setEmployeeNumber(dateStr+"01");
        }
        employeeMapper.insert(employee);
    }

    @Override
    public void deleteById(Integer id) {
        employeeMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            employeeMapper.deleteById(id);
        }
    }

    @Override
    public void updateEmployee(Employee employee) {
        employeeMapper.updateById(employee);
    }

    @Override
    public List<Employee> selectAll(Employee employee) {
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据所选条件进行查询
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(employee.getEmployeeNumber()),Employee::getEmployeeNumber,employee.getEmployeeNumber());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(employee.getDepartmentId()),Employee::getDepartmentId,employee.getDepartmentId());
        lambdaQueryWrapper.orderByDesc(Employee::getId);
        List<Employee> employeeList = employeeMapper.selectList(lambdaQueryWrapper);
        employeeList.forEach( item ->{
            Integer departmentId = item.getDepartmentId();
            Department department = departmentService.selectById(departmentId);
            if (ObjectUtil.isNotEmpty(department)){
                item.setDepartmentName(department.getDepartName());
            }
            if (item.getRole().equals(RoleEnum.USER.name())){
                item.setRole("员工");
            }
            if (item.getRole().equals(RoleEnum.DEPARTMENT_MANAGER.name())){
                item.setRole("部门主管");
            }
            if (item.getRole().equals(RoleEnum.GENERAL_MANAGER.name())){
                item.setRole("总经理");
            }
        });
        return employeeList;
    }

    @Override
    public PageInfo<Employee> selectPage(Employee employee, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Employee user = TokenUtils.getCurrentUser();
        //当用户为主管的时候只能查看部门下的信息
        if (user.getRole().equals(RoleEnum.DEPARTMENT_MANAGER.name())){
            Integer departmentId = user.getDepartmentId();
            lambdaQueryWrapper.eq(Employee::getDepartmentId,departmentId);
        }
        //根据所选条件进行查询
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(employee.getEmployeeNumber()),Employee::getEmployeeNumber,employee.getEmployeeNumber());
        lambdaQueryWrapper.eq(ObjectUtil.isNotEmpty(employee.getDepartmentId()),Employee::getDepartmentId,employee.getDepartmentId());

        lambdaQueryWrapper.orderByDesc(Employee::getId);

        PageHelper.startPage(pageNum, pageSize);
        List<Employee> employeeList = employeeMapper.selectList(lambdaQueryWrapper);
        employeeList.forEach( item ->{
            Integer departmentId = item.getDepartmentId();
            Department department = departmentService.selectById(departmentId);
            if (ObjectUtil.isNotEmpty(department)){
                item.setDepartmentName(department.getDepartName());
            }
            if (item.getRole().equals(RoleEnum.USER.name())){
                item.setRole("员工");
            }
            if (item.getRole().equals(RoleEnum.DEPARTMENT_MANAGER.name())){
                item.setRole("部门主管");
            }
            if (item.getRole().equals(RoleEnum.GENERAL_MANAGER.name())){
                item.setRole("总经理");
            }
        });
        return PageInfo.of(employeeList);
    }

    @Override
    public void register(Employee employee) {
        //注册的时候默认注册员工
        employee.setRole(RoleEnum.USER.name());
        add(employee);
    }

    @Override
    public void updatePassword(Employee employee) {
        //首先判断用户输入的原来密码是否正确
        Employee selectById = employeeMapper.selectById(employee.getId());
        String password = employee.getPassword();
        password = MD5Utils.md5(password);
        if (!selectById.getPassword().equals(password)) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        //如果用户的密码输入正确就进行修改
        Employee update = new Employee();
        update.setId(employee.getId());
        update.setPassword(MD5Utils.md5(employee.getNewPassword()));
        updateById(update);
    }

    @Override
    public Employee selectByName(String name) {
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getName,name);
        Employee employee = employeeMapper.selectOne(lambdaQueryWrapper);
        return employee;
    }
}
